package com.supermap.application.common;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Augustine on 2014/11/5.
 * 动态REST麻点图层切片访问代理服务，如果能解决Tomcat不同工程跨域可并入data
 * （解决跨域、网速慢；高效切片获取）
 */
public class ProxyController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("image/png");
        response.setCharacterEncoding("utf-8");
        String urlStr = request.getParameter("url");//获取请求参数URL
        OutputStream outputStream = response.getOutputStream();
        urlStr = this.handleUrl(urlStr);
        URL url = new URL(urlStr);
        this.getImage(url,outputStream);
    }

    //缓存读取瓦片，显示稳定高效
    private void getImage(URL url, OutputStream out){
        try {
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            byte[] buffer = new byte[512];//缓冲字节数，值小适用网络宽，降低丢包率
            int count = 0;
            while ((count = in.read(buffer)) > 0){
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            connection.disconnect();
        }catch (MalformedURLException e) {
//            e.printStackTrace();
            System.out.println("URL地址出错！");
        }catch (IOException io){
            System.out.println("请求切片，连接超时！");
//            io.printStackTrace();
        }catch (Exception e){
//            e.printStackTrace();
        }
    }

    private void getBufferImage(URL url, OutputStream outputStream){
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setUseCaches(true);

            BufferedInputStream bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            int length = httpURLConnection.getContentLength();
            byte[] buffer = new byte[50];
            int readByte = 0;

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
            while (readByte < length) {
                int num = bufferedInputStream.read(buffer, 0, 50);
                readByte += num;
                bufferedOutputStream.write(buffer, 0, 50);
            }
            if (length == -1) {
                int count = bufferedInputStream.read(buffer, 0, 50);
                while (count != -1) {
                    bufferedOutputStream.write(buffer, 0, count);
                    count = bufferedInputStream.read(buffer, 0, 50);
                }
            }
            bufferedInputStream.close();
            bufferedOutputStream.close();
        } catch (IOException e) {
            System.out.println("请求切片连接超时！");
            e.printStackTrace();
        }
    }


    /**
     * url参数预处理
     * @param url
     * @return
     */
    private String handleUrl(String url){
        //将参数中临时替换的字符替换回来
        url = url.replaceAll("\\$","&");
        url = url.replace("!", "?");

        //将参数中的中文进行编码
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = pattern.matcher(url);
        String zhStr = "";
        while (m.find()) {
            String t = m.group();
            zhStr += t;
        }
        if(!"".equals(zhStr)){
            try {
                url = url.replaceAll(zhStr,URLEncoder.encode(zhStr,"utf-8"));
            } catch (UnsupportedEncodingException e) {
                System.out.println("编码转换出错！ 地图参数中含有中文字符");
                e.printStackTrace();
            }
        }
        return url;
    }

}
